<?php

/**
 * This is the model class for table "mst_struktur_organisasi".
 *
 * The followings are the available columns in table 'mst_struktur_organisasi':
 * @property integer $id
 * @property string $nama
 * @property String[] $tree
 * @property integer $level
 * @property integer $lft
 * @property integer $rgt
 * @property integer $parent_id
 * @property boolean $aktif
 * @property String $tahun
 * @property String[] $BreadPath
 */
class StrukturOrganisasi extends CActiveRecord
{
        public $tree;
        public $BreadPath = array();
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $classnama active record class nama.
	 * @return StrukturOrganisasi the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'mst_struktur_organisasi';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('nama', 'required'),
			//array('level, lft, rgt, root', 'numerical', 'integerOnly'=>true),
			array('nama', 'length', 'max'=>45),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, nama, level, lft, rgt, root', 'safe', 'on'=>'search'),
		);
	}
        
       public function behaviors()
        {
            return array(
                /**
                 * @link http://www.yiiframework.com/extension/nestedsetbehavior/ 
                 */
                'NestedSetBehavior'=>array(
                    'class'=>'ext.yiiext.behaviors.trees.NestedSetBehavior',
                    'leftAttribute'=>'lft',
                    'rightAttribute'=>'rgt',
                    'levelAttribute'=>'level',
                    'hasManyRoots' => TRUE
                    )
            );
        }
        
	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
                    'Child'     => array(self::HAS_MANY, 'StrukturOrganisasi', 'parent_id'),
                    'Parent'    => array(self::BELONGS_TO, 'StrukturOrganisasi', 'id'),
                    'Jabatan'   => array(self::HAS_MANY, 'Jabatan', 'id_struktur_organisasai')
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'nama' => 'Nama',
			'level' => 'Level',
			'lft' => 'Lft',
			'rgt' => 'Rgt',
                        'root' => 'root',
                        'aktif' => 'aktif',
                        'tahun' => 'tahun'
		);
	}
        
        /**
         *
         * @param Int $id
         * @return String[] 
         */
        public function getPath($id) {
            $current        =   $this->findByPk($id);
            $parent         =   $current->parent()->find();
            
            if(!empty($parent))
            {
                if (!in_array($current->nama, $this->BreadPath))
                    $this->BreadPath[] = $current->nama;
                
                if (!in_array($parent->nama, $this->BreadPath))
                    $this->BreadPath[] = $parent->nama;
                
                $this->getPath($parent->id); // recursive
                
            }elseif($current->isRoot()){
                if (!in_array($current->nama, $this->BreadPath))
                    $this->BreadPath[] = $current->nama;
            }
            
            if(is_array($this->BreadPath))
                krsort($this->BreadPath);
            
            return $this->BreadPath;    
        }
        
        /**
         *
         * @param String $id
         * @return boolean 
         */
        public function moveDown($id){
            $data       =   $this->findByPk($id);
            $next       =   $this->next()->find();
            
            if(empty($next))
                return FALSE;
                
            $down     =   $data->findByPk($next->id);
           
            return $data->moveAfter($down);
        }
        
        /**
         *
         * @param String $id
         * @return boolean 
         */
        public function moveUp($id){
            $data       =   $this->findByPk($id);
            $prev       =   $this->prev()->find();
            
            if(empty($prev))
                return FALSE;
                
            $parent     =   $data->findByPk($prev->id);
           
            return $data->moveBefore($parent);
        }
        
        /**
         * reformat List 
         * @return Array
         */
	public function reformatList() {
            $result = array();
            $model  = new StrukturOrganisasi;
            $data   = $model->getList();
            foreach($data as $key=>$value){
                $result[$key] = $value['nama'];
            }
            return $result;
        }

        /**
         * untuk mendapatkan struktur Organisasi dalam bentuk list
         * @access public
         * @return string[] 
         */
        public function getList($id=NULL, $level=1)
        {   
            if($id=="")
            {
                
                $root = $this->roots()->findAll();
                foreach($root as $key=>$value)
                {
                    
                    $jabatan =  Jabatan::model()->findAll(array(
                        'condition' => 't.id_struktur_organisasi='.$value->id
                    ));
                    
                    $this->tree[$value->id] =  array(
                        'nama' => $value->nama,
                        'level'=> $value->level,
                        'parent_id' => $value->parent_id,
                        'tahun' =>$value->tahun,
                        'jumlah_jabatan' => count($jabatan)
                    );
                    $this->getList($value->id, $value->level);
                    
                }
                
            }else{
                
                $root=$this->findByPk($id);
                $child=$root->children()->findAll(array('order'=>'lft ASC'));
                
                foreach($child as $key=>$value){
                    
                    $jabatan =  Jabatan::model()->findAll(array(
                        'condition' => 't.id_struktur_organisasi='.$value->id
                    ));
                    
                    $this->tree[$value->id] = array(
                        'nama' => str_repeat("|-------", $value->level-1) . $value->nama,
                        'level'=> $value->level,
                        'parent_id' => $value->parent_id,
                        'tahun' =>$value->tahun,
                        'jumlah_jabatan' => count($jabatan)
                    );
                     $this->getList($value->id, $value->level); 
                }
            }
                
            return $this->tree;
        }
        
        public function treeGridList(){
            
            /**
             *SELECT node.id, node.nama, node.level, node.parent_id
            FROM mst_struktur_organisasi AS node,
                    mst_struktur_organisasi AS parent
            WHERE node.lft BETWEEN parent.lft AND parent.rgt
                    GROUP BY parent.id
            ORDER BY node.lft; 
             */
            $query = "SELECT node.id, node.nama, node.level, node.parent_id
            FROM mst_struktur_organisasi AS node,
                    mst_struktur_organisasi AS parent
            WHERE node.lft BETWEEN parent.lft AND parent.rgt
                    GROUP BY parent.id
            ORDER BY node.lft";
            
            $criteria = new CDbCriteria;
            $criteria->order = 'lft asc';
            //die;
            $rawData=Yii::app()->db->createCommand($query)->queryAll();
            // or using: $rawData=User::model()->findAll();
            return new CActiveDataProvider($this, array(
                'criteria'=>$criteria,
                'pagination'=>FALSE
            ));
            
        }
        
	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('nama',$this->nama,true);
		$criteria->compare('level',$this->level);
		$criteria->compare('lft',$this->lft);
		$criteria->compare('rgt',$this->rgt);
		$criteria->compare('root',$this->root);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
}